package yxy.game.pm2.module.chat;

import org.joda.time.DateTime;
import org.redisson.api.RMap;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.module.BaseGameRedisBean;

/**
 *
 * <pre>
 *     定时清除数据程序请看{@link yxy.cherry.gm.task.Chat.CleanChatBlackTask}
 *</pre>
 * 禁言表
 * */
public class Banned extends BaseGameRedisBean {

	static Banned instance;

	public static Banned getInstance() {
		if (instance == null) {
			instance = new Banned();
		}
		return instance;
	}

	// redis==========================================================================

	static public String key() {
		return "CHAT:BANNED";
	}

	static private RMap<String, Long> touch() throws RedisException {
		return RedisManager.client(redis()).getMap(key());
	}

	public void set(PlayerBean player, DateTime liftTime) {
		try {
			long time = 0;// 为0 永久禁言
			if (liftTime != null) {
				time = liftTime.getMillis();
			}
			touch().put(player.getCode(), time);
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	public void remove(String playerCode) {
		try {
			touch().remove(playerCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean isBanned(String playerCode) {
		try {
			RMap<String, Long> rmap = touch();
			if (rmap.size() == 0) {
				rmap.put("a", 0L);
			}
			if (rmap.containsKey(playerCode)) {
				long time = rmap.get(playerCode);
				return time <= 0 || System.currentTimeMillis() < time;
			}
		} catch (Exception e) {
		}
		return false;
	}

	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key());
	}

}
